import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Swagger 配置选项
const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'StoryPlush API 文档',
      version: '1.0.0',
      description: 'StoryPlush项目API接口文档',
      contact: {
        name: '开发团队'
      }
    },
    servers: [
      {
        url: 'http://localhost:5000',
        description: '开发服务器'
      }
    ],
    components: {
      securitySchemes: {
        BearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT'
        }
      }
    }
  },
  // 指定包含API注释的路径，使用绝对路径增加可靠性
  apis: [
    path.resolve(__dirname, '../routes/*.js'), 
    path.resolve(__dirname, '../models/*.js'), 
    path.resolve(__dirname, '../services/*.js'), 
    path.resolve(__dirname, '../index.js')
  ]
};

// 生成Swagger规范
const specs = swaggerJsdoc(options);

// 自定义HTML文档页面
const htmlContent = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>StoryPlush API 文档</title>
    <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.0.0/swagger-ui.css">
    <style>
        body { margin: 0; padding: 0; }
        #swagger-ui { max-width: 1200px; margin: 0 auto; }
        .swagger-ui .topbar { display: none; }
    </style>
</head>
<body>
    <div id="swagger-ui"></div>
    <script src="https://unpkg.com/swagger-ui-dist@5.0.0/swagger-ui-bundle.js"></script>
    <script>
        window.onload = function() {
            window.ui = SwaggerUIBundle({
                spec: ${JSON.stringify(specs)},
                dom_id: '#swagger-ui',
                presets: [
                    SwaggerUIBundle.presets.apis,
                    SwaggerUIBundle.SwaggerUIStandalonePreset
                ],
                layout: "BaseLayout",
                deepLinking: true,
                docExpansion: "list"
            });
        }
    </script>
</body>
</html>
`;

// 导出Swagger配置和UI中间件
export const swaggerSetup = (app) => {
  // 添加调试日志
  console.log('设置Swagger文档路径: /api-docs');
  
  // 使用内嵌HTML方式提供文档
  app.get('/api-docs', (req, res) => {
    res.setHeader('Content-Type', 'text/html');
    res.send(htmlContent);
  });
  
  // 保留原始的swagger-ui方式作为备选
  app.use('/api-docs-ui', swaggerUi.serve, swaggerUi.setup(specs, {
    explorer: true,
    customCss: '.swagger-ui .topbar { display: none }',
    customSiteTitle: "StoryPlush API 文档"
  }));
  
  // 添加JSON规范端点，用于自定义Swagger页面
  app.get('/api-docs-json', (req, res) => {
    console.log('提供API文档JSON规范');
    res.setHeader('Content-Type', 'application/json');
    res.send(specs);
  });
  
  // 添加一个简单的测试路由来检查Swagger是否正常工作
  app.get('/api-docs-test', (req, res) => {
    res.json({
      message: 'Swagger文档服务正常工作',
      endpoints: {
        documentation: '/api-docs',
        jsonSpec: '/api-docs-json',
        alternativeUI: '/api-docs-ui',
        testPage: '/swagger-test.html',
        customUI: '/swagger.html'
      }
    });
  });
  
  // 确保public目录存在并创建swagger-test.html
  const publicDir = path.join(__dirname, '../../public');
  if (!fs.existsSync(publicDir)) {
    fs.mkdirSync(publicDir, { recursive: true });
    console.log(`Created public directory: ${publicDir}`);
  }
  
  // 记录所有已注册的路由
  console.log('API路由列表:');
  app._router.stack
    .filter(r => r.route && r.route.path)
    .forEach(r => console.log(`${Object.keys(r.route.methods).join(',')} ${r.route.path}`));
};

export default specs; 